package com.istock.monitor.agent.transformer;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.List;

import com.istock.monitor.agent.util.ClassUtils;

/**
 * 在正常的jvm里面,因为存在jvm的依赖限制
 * agent的代码无法依赖web容器加载的类
 * 
 * 本类就是为了解决这个问题
 * 
 * @author senvon
 *
 */
public class SpringInitialLoaderTransform implements ClassFileTransformer {

	
	private List<byte[]> classList; 
	
	public SpringInitialLoaderTransform(List<byte[]> classList){
		this.classList = classList;
	}
	
	@Override
	public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
			ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
		
		if(className.equalsIgnoreCase("org/springframework/web/context/support/AbstractRefreshableWebApplicationContext")) {
			//加载到spring的时候,使用当前的classloader,加载agent中依赖war的类
			try{
				for(byte[] item : classList){
					System.out.println("=================ready to load=================");
					ClassUtils.transferClass(loader, item);
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		
		return null;
	}

}
